package com.xinghou.platform.server.api.bussiness.impl;

import com.xinghou.platform.dao.bases.util.StringUtils;
import com.xinghou.platform.dao.main.FavoriteDAO;
import com.xinghou.platform.dao.main.SubjectDAO;
import com.xinghou.platform.dao.main.UserDAO;
import com.xinghou.platform.entity.req.ListReq;
import com.xinghou.platform.entity.resp.SubjectResp;
import com.xinghou.platform.entity.resp.UserInfoResp;
import com.xinghou.platform.model.main.Subject;
import com.xinghou.platform.model.main.SubjectReply;
import com.xinghou.platform.model.main.SubjectReplyPraise;
import com.xinghou.platform.server.api.bussiness.SubjectService;
import com.xinghou.platform.server.api.bussiness.UserInfoBusinessService;
import com.xinghou.platform.server.api.log.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by qingshengzheng on 16/6/23.
 */
@Service("SubjectService")
public class SubjectServiceImpl implements SubjectService {

    private Logger logInfo = LoggerFactory.getServerInfoLogger(SubjectServiceImpl.class);
    @Resource
    private SubjectDAO subjectDAO;

    @Resource
    private FavoriteDAO favoriteDAO;

    @Resource

    private UserDAO userDAO;

    @Autowired UserInfoBusinessService userService;




    @Override
    public Integer pubSubject(Subject subject ,String joinnum) {
        subject.createtime=System.currentTimeMillis();
        if(StringUtils.isNullOrEmpty(String.valueOf(subject.pubtime))) {
            subject.pubtime=System.currentTimeMillis();
        }
        subjectDAO.pubSubject(subject);
        Long joinnumber = 0l;
        if(!StringUtils.isNullOrEmpty(joinnum)){
            joinnumber=Long.parseLong(joinnum);
        }
        subjectDAO.insertSubjectStatistics(subject.getId(),joinnumber);
        return subject.id.intValue();
    }

    @Override
    public void updateSubject(Subject subject,String joinnum) {
        subjectDAO.updateSubject(subject);
        if(!StringUtils.isNullOrEmpty(joinnum)){
            subjectDAO.editSubjectJoinNum(subject.getId(),Integer.parseInt(joinnum));
        }
    }

    @Override
    public void updateSubjectReply(SubjectReply subjectReply) {
        subjectReply.updatetime=System.currentTimeMillis();
        subjectDAO.updateSubjectReply(subjectReply);

    }

    @Override
    public void delSubject(Long id,String operator) {
        subjectDAO.delSubject(id,operator);
    }

    @Override
    public SubjectResp subjectDetail(Long uid,Long id) {

        Subject subject = subjectDAO.getSubjectDetail(id);
        SubjectResp subjectResp = SubjectResp.initFromSubject(subject);
        UserInfoResp user =  userService.getUserInfo(String.valueOf(subject.uid),String.valueOf(subject.uid));
        subjectResp.joinnum = getSubjectJoinNumber(subject.id);
        subjectResp.replynum = getSubjectReplyNumber(subject.id);
        if(user !=null) {
            subjectResp.nickname =user.getNickname();
            subjectResp.headurl= user.getHeadurl();
        }
        SubjectReply reply = getMostHotReply(subject.id);
        String isfavorite =  "";
        if(!StringUtils.isNullOrEmpty(String.valueOf(uid))){

            isfavorite =    String.valueOf(favoriteDAO.hasFavoritySubject(uid,subject.id));
        }
        if(StringUtils.isNullOrEmpty(isfavorite))  {
            subjectResp.isfavorite="";
        }else{
            subjectResp.isfavorite=isfavorite;
        }
        if(reply!= null){
            subjectResp.hotreply = reply.getDescription();


        }
        return subjectResp;
    }
    @Override
    public void addSubjectJoinNum(Long uid, Long subjectid){
         subjectDAO.addSubjectJoinNum(subjectid,uid);
    }


    @Override
    public Long subjectReply(SubjectReply reply,String from) {
        reply.createtime=System.currentTimeMillis();
        if(null==reply.replyTime||reply.replyTime<=0l){
            reply.replyTime=System.currentTimeMillis();
        }
    /*   if(null==reply.replyTime&&!StringUtils.isNullOrEmpty(from)&&"3".equals(from)){
           Subject subject= subjectDAO.getSubjectDetail(reply.subjectid);
            reply.replyTime= subject.pubtime+ (int)(Math.random()*60*60*24*1000);
        }else{
            reply.replyTime=System.currentTimeMillis();
        }*/
        subjectDAO.subjectReply(reply);
        return reply.id;

    }

    @Override
    public void delSubjectReply(Long replyid,Long subjectid) {
        subjectDAO.delSubjectReply(replyid, subjectid);

    }

    @Override
    public List<SubjectReply> getHotReplys(Long id,String uid) {
        Long nowtime = System.currentTimeMillis();
        List<String> replyIds = subjectDAO.getHotReplyIds(id, 5,nowtime);

        return getReplysByIds(replyIds,uid);
    }

    @Override
    public List<SubjectReply> hotSubjectReplysList(Long id,String uid) {
        List<String> replyIds = subjectDAO.hotSubjectReplysList(id, 5);

        return getReplysByIds(replyIds,uid);
    }


    public List<SubjectReply> getReplysByIds(List<String> ids,String uid) {
        List<SubjectReply> replys = new ArrayList<SubjectReply>();
        Long nowtime =System.currentTimeMillis();
        for (int i = 0; i < ids.size(); i++) {
            SubjectReply reply = subjectDAO.getSubjectReplyById(Long.parseLong(ids.get(i)));
            if(reply!=null) {
                UserInfoResp user = userService.getUserInfo(String.valueOf(reply.getUid()), String.valueOf(reply.getUid()));
                if (user != null) {
                    reply.userName = user.getNickname();
                    reply.userHead = user.getHeadurl();
                    reply.praise_count = getSubjectReplyPaiseCount(reply.getId());
                    reply.timestamp=nowtime;
                    if (uid == null || "".equals(uid)) {
                        reply.ispraised = false;
                    } else {
                        reply.ispraised = isPraised(reply.getId().toString(), uid);
                    }
                }
                replys.add(reply);
            }

        }
        return replys;
    }


    @Override
    public List<SubjectReply> getReplys(Long subjectid,String startno, String rownum,String uid,String direction,String timestamp) {
        List<SubjectReply> replys =null;

        Long nowtime = System.currentTimeMillis();
        if(StringUtils.isNullOrEmpty(timestamp) && StringUtils.isNullOrEmpty(direction)){
            replys = subjectDAO.getReplys(subjectid,Long.parseLong(startno), Integer.parseInt(rownum),nowtime);
        }else {
            if("1".equals(direction)){
                replys = subjectDAO.getReplysByTimestampUp(subjectid, Long.parseLong(timestamp), Integer.parseInt(rownum),nowtime);
            }else if ("-1".equals(direction)){
                replys = subjectDAO.getReplysByTimestampDown(subjectid, Long.parseLong(timestamp), Integer.parseInt(rownum),nowtime);
            }


        }

        for( SubjectReply reply :replys) {
            UserInfoResp user = userService.getUserInfo(String.valueOf(reply.getUid()),String.valueOf(reply.getUid()));
            if(user !=null) {
                reply.timestamp=nowtime;
                reply.userName =user.getNickname();
                reply.userHead =user.getHeadurl();
                reply.praise_count=getSubjectReplyPaiseCount(reply.getId());
                if(uid==null||"".equals(uid)){
                    reply.ispraised=false;
                }else{
                    reply.ispraised=isPraised(reply.getId().toString(),uid);
                }

            }


        }
        return replys;
    }

    @Override
    public List<SubjectReply> subjectReplyList(ListReq listReq) {
        List<SubjectReply> replys = subjectDAO.subjectReplyList(listReq);
        for( SubjectReply reply :replys) {
            UserInfoResp user = userService.getUserInfo(String.valueOf(reply.getUid()), String.valueOf(reply.getUid()));
            if(user !=null) {
                reply.userName =user.getNickname();
                reply.userHead =user.getHeadurl();
                reply.praise_count=getSubjectReplyPaiseCount(reply.getId());
            }

        }
        return replys;
    }

    @Override
    public List<SubjectResp> getSubjects(Long startno, int rownum,String uid) {
        Long timestamp = System.currentTimeMillis();
        List<Subject> subjects = subjectDAO.getSubjects(startno, rownum,timestamp);
        List<SubjectResp> respList = new ArrayList<SubjectResp>();
        for(Subject subject :subjects) {
            SubjectResp subjectResp= SubjectResp.initFromSubject(subject);
            subjectResp.joinnum = getSubjectJoinNumber(subject.id);
            subjectResp.replynum = getSubjectReplyNumber(subject.id);
            subjectResp.sharenum = getSubjectShareNumber(subject.id);
            subjectResp.clicknum = getSubjectClickNumber(subject.id);
       /*    UserInfoResp user =userService.getUserInfo(String.valueOf(subject.uid),"0","1");*/
            SubjectReply reply = getMostHotReply(subject.id);
            String isfavorite =  "";
            if(!StringUtils.isNullOrEmpty(uid)){

               isfavorite =    String.valueOf(favoriteDAO.hasFavoritySubject(Long.parseLong(uid),subject.id));
            }
            if(StringUtils.isNullOrEmpty(isfavorite))  {
                subjectResp.isfavorite="";
            }else{
                subjectResp.isfavorite=isfavorite;
            }
            if(reply!= null){
                subjectResp.hotreply = reply.getDescription();


            UserInfoResp user =  userService.getUserInfo(String.valueOf(reply.uid),String.valueOf(reply.uid));
            if(user !=null) {
                subjectResp.username =user.getNickname();
                subjectResp.userhead =user.getHeadurl();
            }else{
                subjectResp.username ="";
                subjectResp.userhead ="";
            }
            }else{
                subjectResp.hotreply ="";
                subjectResp.username ="";
                subjectResp.userhead ="";
            }
            respList.add(subjectResp);
        }
        return respList;
    }

    @Override
    public List<SubjectResp> getSubjectList(ListReq listReq) {
        List<Subject> subjects = subjectDAO.getSubjectList(listReq);
        List<SubjectResp> respList = new ArrayList<SubjectResp>();
        for(Subject subject :subjects) {
            SubjectResp subjectResp= SubjectResp.initFromSubject(subject);
            subjectResp.joinnum = getSubjectJoinNumber(subject.id);
            subjectResp.replynum = getSubjectReplyNumber(subject.id);
            subjectResp.sharenum = getSubjectShareNumber(subject.id);
            subjectResp.clicknum = getSubjectClickNumber(subject.id);
            subjectResp.realjoinnum= getSubjectRealJoinNumber(subject.id);
       /*    UserInfoResp user =userService.getUserInfo(String.valueOf(subject.uid),"0","1");*/
            SubjectReply reply = getMostHotReply(subject.id);
            if(reply!= null){
                subjectResp.hotreply = reply.getDescription();
            }else{
                subjectResp.hotreply ="";
            }
          //  subjectResp.isfavorite=String.valueOf(favoriteDAO.hasFavoritySubject(Long.parseLong(uid),subject.id));
            UserInfoResp user =  userService.getUserInfo(String.valueOf(subject.uid),String.valueOf(subject.uid));
            if(user !=null) {
                subjectResp.username =user.getNickname();
                subjectResp.userhead =user.getHeadurl();
            }else{
                subjectResp.username ="";
                subjectResp.userhead ="";
            }
            respList.add(subjectResp);
        }
        return respList;
    }

    @Override
    public SubjectResp subjectDetailInfo(Long uid, Long subjectid)
    {
      Subject  subject=subjectDAO.getSubjectDetail(subjectid);
        if(subject==null) return null;
        SubjectResp subjectResp= SubjectResp.initFromSubject(subject);
        subjectResp.joinnum = String.valueOf(getSubjectJoinNumber(subjectid));
        subjectResp.replynum = String.valueOf(getSubjectReplyNumber(subjectid));
       /*    UserInfoResp user =userService.getUserInfo(String.valueOf(subject.uid),"0","1");*/
        SubjectReply reply = getMostHotReply(subject.id);

        subjectResp.isfavorite=String.valueOf(favoriteDAO.hasFavoritySubject(Long.parseLong(uid.toString()),subject.id));
        if(reply!= null){
            subjectResp.hotreply = reply.getDescription();
            UserInfoResp user =  userService.getUserInfo(String.valueOf(reply.uid),String.valueOf(reply.uid));
                subjectResp.username =user.getNickname();
                subjectResp.userhead =user.getHeadurl();

        }else{
            subjectResp.hotreply ="";
        }


        return subjectResp;
    }




    @Override
    public Subject getLastSubject() {

        Long timestamp =System.currentTimeMillis();
        return subjectDAO.getLastSubject(timestamp);
    }

    @Override
    public SubjectResp getLastSubjectResp() {
        SubjectResp resp = new SubjectResp();
        Subject subject = getLastSubject();
        if(subject==null){
            return null;
        }
        String joinNum = subjectDAO.getSubjectJoinNumber(subject.id);
        String replyNumber = subjectDAO.getSubjectReplyNumber(subject.id);
        resp = resp.initFromSubject(subject);
        resp.joinnum = joinNum;
        resp.replynum= replyNumber;
        return resp;
    }

    @Override
    public void likeReply(SubjectReplyPraise subjectReplyPraise){
        subjectReplyPraise.createtime=String.valueOf(System.currentTimeMillis());
        subjectReplyPraise.updatetime=String.valueOf(System.currentTimeMillis());
        subjectDAO.likeReply(subjectReplyPraise);
        subjectDAO.updateLikeCount(Long.parseLong(subjectReplyPraise.getReplyid()));

    }
    @Override
    public boolean isPraised(String replyid, String uid) {
        return subjectDAO.isPraised(replyid, uid) ;
    }

    @Override
    public List<Subject> getLastThreeDaySubject() {
        Calendar calender = Calendar.getInstance();
        calender.add(Calendar.DATE, -3);

        Long timestamp =calender.getTimeInMillis();
        Long nowtime =System.currentTimeMillis();
        return subjectDAO.getLastThreeDaySubject(timestamp,nowtime);
    }

    @Override
    public List<SubjectReply> getUserSubjectReply(ListReq listReq){
        return subjectDAO.getUserSubjectReply(listReq);
    }


    public String getSubjectJoinNumber(Long subject){
        return subjectDAO.getSubjectJoinNumber(subject);
    }

    public String getSubjectRealJoinNumber(Long subject){
        return subjectDAO.getSubjectRealJoinNumber(subject);
    }

    public String getSubjectReplyNumber(Long subject){
        return subjectDAO.getSubjectReplyNumber(subject);
    }

    public String getSubjectShareNumber(Long subject){
        return subjectDAO.getSubjectShareNumber(subject);
    }

    public String getSubjectClickNumber(Long subject){
        return subjectDAO.getSubjectClickNumber(subject);
    }


    public SubjectReply getMostHotReply(Long id) {
        Long nowtime =System.currentTimeMillis();
        List<String> replyIds = subjectDAO.getHotReplyIds(id,5,nowtime);
        if (replyIds==null ||replyIds.size()==0){
            return null;
        }
        //int scope= (int)(Math.random()*replyIds.size());
        int scope= 1;
        if(scope==0){
            scope=1;
        }
        return subjectDAO.getSubjectReplyById(Long.parseLong(replyIds.get(scope-1)));
    }

    public Long getSubjectReplyPaiseCount(Long replyid){
        return subjectDAO.getSubjectReplyPaiseCount(replyid);
    }

    public void updateSubjectShareCount(String subjectid) {
        subjectDAO.updateSubjectShareCount(subjectid);
    }

    public void updateSubjectClickCount(String subjectid) {
        subjectDAO.updateSubjectClickCount(subjectid);
    }

    protected String longToDate(Long Longtime){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(Longtime);
        return sdf.format(date);
    }
    public void updateRandomJoinnum(Long subjectid,int randomjoinnumber){

        subjectDAO.updateRandomJoinnum(subjectid, randomjoinnumber);
    }
}
